/**
 * Created by jinkailong on 2019/3/6.
 */

#include <jni.h>
#include <string.h>
#include "include/AudioResample.h"
#include "include/AILog.h"


#ifdef __cplusplus
extern "C" {
#endif

#ifdef __cplusplus
#define __STDC_CONSTANT_MACROS
#ifdef _STDINT_H
#undef _STDINT_H
#endif
#include <stdint.h>
#endif

JNIEXPORT jlong JNICALL
Java_com_wbvideo_resample_AudioReSampleUtils_initReSample(JNIEnv *env, jclass type,
                                                            jint inChannels, jint inSampleRate,
                                                            jint outChannels, jint outSampleRate) {

    LOGI("nativeInitReSampler");
    AudioResample *resample = new AudioResample;
    resample->initResample(inChannels, inSampleRate, outChannels, outSampleRate);
    return (long) resample;

}

JNIEXPORT jbyteArray JNICALL
Java_com_wbvideo_resample_AudioReSampleUtils_reSampleBuffer(JNIEnv *env, jclass type, jlong obj,
                                                              jbyteArray buffer_, jint bytelen) {

    if (!buffer_) {
        return buffer_;
    }
    jbyte *buffer = env->GetByteArrayElements(buffer_, NULL);
    int dataLen = env->GetArrayLength(buffer_);

    AudioResample *resample = (AudioResample *) obj;
    int dst_bufsize = 0;
    jbyte *bufferResult = resample->resample(buffer, bytelen, &dst_bufsize);

    jbyteArray result = env->NewByteArray(dst_bufsize);
    env->SetByteArrayRegion(result, 0, (jsize) dst_bufsize, bufferResult);

    env->ReleaseByteArrayElements(buffer_, buffer, 0);
    return result;
}

JNIEXPORT void JNICALL
Java_com_wbvideo_resample_AudioReSampleUtils_endResample(JNIEnv *env, jclass type, jlong obj) {
    AudioResample *resample = (AudioResample *) obj;
    resample->end();
}

#ifdef __cplusplus
}
#endif